import 'dart:io';
import 'package:get/get.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

// 页面缓存模型
class PageCacheModel {
  String pageKey;
  String data;
  int timestamp;
  dynamic extraInfo;

  PageCacheModel({
    required this.pageKey,
    required this.data,
    required this.timestamp,
    this.extraInfo,
  });

  Map<String, dynamic> toMap() {
    return {
      'page_key': pageKey,
      'data': data,
      'timestamp': timestamp,
      'extra_info': extraInfo,
    };
  }
}

// 页面缓存服务
class PageCacheService extends GetxService {
  // 页面缓存服务
  static PageCacheService get to => Get.find();

  static const _databaseName = 'app_page_cache.db';
  static const _databaseVersion = 1;

  Database? _database;

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  // 初始化数据库
  Future<Database> _initDatabase() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, _databaseName);

    return await openDatabase(
      path,
      version: _databaseVersion,
      onCreate: _onCreate,
      onUpgrade: _onUpgrade,
    );
  }

  // 创建表
  Future<void> _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE page_cache (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        page_key TEXT UNIQUE NOT NULL,
        data TEXT NOT NULL,
        timestamp INTEGER NOT NULL,
        extra_info TEXT
      )
    ''');

    // 创建索引提高查询性能
    await db.execute('CREATE INDEX idx_page_key ON page_cache (page_key)');
  }

  // 数据库升级
  Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
    if (oldVersion < newVersion) {
      // 这里可以添加升级逻辑
      // 例如：添加新列、修改表结构等
    }
  }

  // 保存页面数据
  Future<void> savePageData({
    required String pageKey,
    required String data,
    Map<String, dynamic>? extraInfo,
  }) async {
    final db = await database;

    await db.insert(
      'page_cache',
      {
        'page_key': pageKey,
        'data': data,
        'timestamp': DateTime.now().millisecondsSinceEpoch,
        'extra_info': extraInfo?.toString(),
      },
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  // 获取页面数据
  Future<PageCacheModel?> getPageData(String pageKey) async {
    final db = await database;

    final result = await db.query(
      'page_cache',
      where: 'page_key = ?',
      whereArgs: [pageKey],
      limit: 1,
    );

    if (result.isNotEmpty) {
      return PageCacheModel(
        pageKey: result.first['page_key'] as String,
        data: result.first['data'] as String,
        timestamp: result.first['timestamp'] as int,
        extraInfo: result.first['extra_info'],
      );
    }

    return null;
  }

  // 清除指定页面缓存
  Future<bool> clearPageCache(String pageKey) async {
    final db = await database;
    return await db.delete(
      'page_cache',
      where: 'page_key = ?',
      whereArgs: [pageKey],
    ).then((value) => value > 0);
  }

  // 清除所有过期缓存 (days: 过期天数)
  Future<bool> clearExpiredCache({int days = 30}) async {
    final db = await database;
    final threshold =
        DateTime.now().subtract(Duration(days: days)).millisecondsSinceEpoch;

    return await db.delete(
      'page_cache',
      where: 'timestamp < ?',
      whereArgs: [threshold],
    ).then((value) => value > 0);
  }

  // 清除所有缓存
  Future<bool> clearAllCache() async {
    final db = await database;
    return await db.delete('page_cache').then((value) => value > 0);
  }

  // 获取缓存大小 (字节)
  Future<int> getCacheSize() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, _databaseName);
    final file = File(path);
    if (await file.exists()) {
      return await file.length();
    }
    return 0;
  }
}
